<template>
  <com-page>
    <u-navbar :title="$t('pages_user_address_edit_msg_505ea466')"
              placeholder
              autoBack>
      <view slot="right"
            class="com-color-tips com-m-md"
            @click="onDelete">删除</view>
    </u-navbar>
    <form @submit="onSubmit">
      <view class="com-section">
        <view class="com-cell">
          <view class="com-cell__hd">联系人</view>
          <view class="com-cell__bd">
            <input :value="address.name"
                   name="name"
                   :placeholder="$t('pages_user_address_edit_desc_1521d92d')">
          </view>
        </view>
        <view class="com-cell">
          <view class="com-cell__hd">手机号</view>
          <view class="com-cell__bd">
            <input :value="address.phone"
                   name="phone"
                   :placeholder="$t('pages_user_address_edit_desc_a11d70c0')">
          </view>
        </view>
        <view class="com-cell com-flex">
          <view class="com-cell__hd">收货地址</view>
          <picker mode="multiSelector"
                  @change="bindMultiPickerChange"
                  @columnchange="bindMultiPickerColumnChange"
                  :value="multiIndex"
                  :range="areaList"
                  range-key="name"
                  class="com-flex-1">
            <view class="com-cell__bd com-flex">
              <u-icon name="location"
                      custom-prefix="icon"
                      class="com-color-primary com-mr-xs com-text-md" />
              <input :value="addressAll"
                     name="address"
                     class="com-text-cut"
                     style="width: 100%"
                     :placeholder="$t('pages_user_address_edit_desc_4a046009')"
                     disabled="true">
            </view>
          </picker>
          <view class="com-arrow" />
        </view>
        <view class="com-cell">
          <view class="com-cell__hd">详细地址</view>
          <view class="com-cell__bd">
            <textarea name="detailAddress"
                      :value="address.detailAddress"
                      placeholder="如道路、门牌号、小区、楼栋好、单元室等"
                      style="width: 100%; height: 100rpx" />
          </view>
        </view>
      </view>

      <view class="com-section">
        <view class="com-cell">
          <view class="com-cell__hd">地址标签</view>
          <view class="com-cell__ft">
            <view @click="onTag"
                  data-tag="1"
                  :class="['com-button', 'sm', 'com-round', 'com-ml-sm', address.tag == '1' ? 'com-color-primary-bg' : '']">家</view>
            <view @click="onTag"
                  data-tag="2"
                  :class="['com-button', 'sm', 'com-round', 'com-ml-sm', address.tag == '2' ? 'com-color-primary-bg' : '']">公司</view>
            <view @click="onTag"
                  data-tag="3"
                  :class="['com-button', 'sm', 'com-round', 'com-ml-sm', address.tag == '3' ? 'com-color-primary-bg' : '']">学校</view>
          </view>
        </view>
        <view class="com-cell align-center">
          <view class="com-cell__hd">设置默认地址</view>
          <view class="com-cell__ft">
            <switch name="default"
                    :checked="address.isDefault == 1 || address.defaultStatus == 1"
                    @change="defalutChange"
                    style="zoom: 0.6" />
          </view>
        </view>
      </view>

      <button form-type="submit"
              class="com-button block com-round com-color-primary-bg com-m-md"
              style="width: auto">保存</button>
    </form>
  </com-page>
</template>

<script>
import { createAddress, updateAddress, getAddressList, deleteAddress } from '@/api/modules/user'

export default {
  name: 'Address-Edit',
  data() {
    return {
      isEdit: false,
      addressId: null,
      address: {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        postCode: '',
        defaultStatus: 0,
        isDefault: 0
      },
      addressAll: '',
      areaList: [
        [
          { name: this.$t('pages_user_address_edit_msg_f383e7e9'), code: '430000' },
          { name: this.$t('pages_user_address_edit_msg_ab5cbe45'), code: '440000' },
          { name: this.$t('pages_user_address_edit_msg_a8e56248'), code: '110000' }
        ],
        [
          { name: this.$t('pages_user_address_edit_msg_d9716334'), code: '430100' },
          { name: this.$t('pages_user_address_edit_msg_579c173e'), code: '430400' },
          { name: this.$t('pages_user_address_edit_msg_f0d68d9c'), code: '430200' }
        ],
        [
          { name: this.$t('pages_user_address_edit_msg_6ed8a951'), code: '430104' },
          { name: this.$t('pages_user_address_edit_msg_088845e6'), code: '430102' },
          { name: this.$t('pages_user_address_edit_msg_87a8b5c9'), code: '430103' }
        ]
      ],
      multiIndex: [0, 0, 0],
      tagType: {
        1: this.$t('pages_user_address_edit_text_a6cdd2a0'),
        2: this.$t('pages_user_address_edit_text_41716f87'),
        3: this.$t('pages_user_address_edit_text_413b7380')
      }
    }
  },
  onLoad(options) {
    if (options && options.id) {
      this.isEdit = true
      this.addressId = options.id
      this.getAddressDetail()
    } else {
      this.updateAddressAll()
    }
  },
  methods: {
    async getAddressDetail() {
      try {
        const res = await getAddressList()
        const addressData = res.find(item => item.id == this.addressId)
        if (addressData) {
          this.address = { ...addressData }
          this.updateAddressAll()
        }
      } catch (error) {
        this.$utils.toast(this.$t('pages_user_address_edit_desc_b5c976b8'))
      }
    },

    updateAddressAll() {
      const { province, city, district } = this.address
      this.addressAll = `${province || ''} ${city || ''} ${district || ''}`.trim()
    },

    async onSubmit(event) {
      const value = event.detail.value
      
      if (!this.validateForm(value)) {
        return
      }

      const submitData = {
        name: value.name.trim(),
        phone: value.phone.trim(),
        province: this.address.province,
        city: this.address.city,
        district: this.address.district,
        detailAddress: value.detailAddress.trim(),
        postCode: this.address.postCode || '',
        defaultStatus: value.default ? 1 : 0,
        isDefault: value.default ? 1 : 0
      }

      if (this.isEdit) {
        submitData.id = this.addressId
      }

      uni.showLoading({
        title: this.isEdit ? '修改中...' : '添加中...'
      })

      try {
        const res = this.isEdit 
          ? await updateAddress(submitData)
          : await createAddress(submitData)
        
        this.$utils.toast(this.isEdit ? '修改成功' : this.$t('pages_user_address_edit_msg_3fdaeadf'))
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('提交地址失败:', error)
        this.$utils.toast(this.isEdit ? '修改失败' : this.$t('pages_user_address_edit_msg_6452a055'))
      } finally {
        uni.hideLoading()
      }
    },

    validateForm(value) {
      if (!value.name || !value.name.trim()) {
        this.$utils.toast(this.$t('pages_user_address_edit_msg_9e3f21b3'))
        return false
      }
      if (!value.phone || !value.phone.trim()) {
        this.$utils.toast(this.$t('pages_user_address_edit_desc_7b540b80'))
        return false
      }
      if (!/^1[3-9]\d{9}$/.test(value.phone.trim())) {
        this.$utils.toast(this.$t('pages_user_address_edit_desc_9f663308'))
        return false
      }
      if (!this.addressAll) {
        this.$utils.toast(this.$t('pages_user_address_edit_msg_07548893'))
        return false
      }
      if (!value.detailAddress || !value.detailAddress.trim()) {
        this.$utils.toast(this.$t('pages_user_address_edit_desc_80d6852f'))
        return false
      }
      return true
    },

    bindMultiPickerChange(e) {
      const { value } = e.detail
      this.multiIndex = value
      
      this.address.province = this.areaList[0][value[0]].name
      this.address.city = this.areaList[1][value[1]].name
      this.address.district = this.areaList[2][value[2]].name
      
      this.updateAddressAll()
    },

    bindMultiPickerColumnChange(e) {
      const { column, value } = e.detail
      this.multiIndex[column] = value
      
      if (column === 0) {
        this.multiIndex[1] = 0
        this.multiIndex[2] = 0
      } else if (column === 1) {
        this.multiIndex[2] = 0
      }
    },

    onTag(e) {
      const tag = e.currentTarget.dataset.tag
      this.address.tag = tag
    },

    defalutChange(e) {
      this.address.isDefault = e.detail.value ? 1 : 0
      this.address.defaultStatus = e.detail.value ? 1 : 0
    },

    async onDelete() {
      if (!this.isEdit) return
      
      const confirmRes = await uni.showModal({
        title: this.$t('pages_category_category_text_02d9819d'),
        content: '确定要删除该地址吗？'
      })
      
      if (confirmRes.confirm) {
        try {
          const res = await deleteAddress(this.addressId)
          this.$utils.toast(this.$t('pages_user_address_address_msg_0007d170'))
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } catch (error) {
          this.$utils.toast(this.$t('pages_user_address_address_msg_acf0664a'))
        }
      }
    }
  },
}
</script>

<style lang="scss" scoped></style>
